package com.pai4j.zwiki.domain.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

/**
 * ZWiki任务队列实体
 * 记录所有待处理和正在处理的任务
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "zwiki_task_queue", indexes = {
        @Index(name = "idx_task_id", columnList = "taskId"),
        @Index(name = "idx_status", columnList = "status"),
        @Index(name = "idx_priority", columnList = "priority"),
        @Index(name = "idx_created_at", columnList = "createdAt")
})
@EntityListeners(AuditingEntityListener.class)
public class ZWikiTaskQueueEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 任务ID（UUID）
     */
    @Column(nullable = false, unique = true, length = 64)
    private String taskId;

    /**
     * 用户ID
     */
    @Column(nullable = false)
    private Long userId;

    /**
     * 任务类型：project_analysis（项目分析）, thesis_generation（论文生成）
     */
    @Column(nullable = false, length = 50)
    private String taskType;

    /**
     * 任务状态：pending（等待）, processing（处理中）, completed（已完成）, failed（失败）
     */
    @Column(nullable = false, length = 20)
    private String status;

    /**
     * 优先级：1-低，3-普通，5-高，10-紧急
     */
    @Column(nullable = false)
    @Builder.Default
    private Integer priority = 3;

    /**
     * 任务数据（JSON格式）
     */
    @Column(columnDefinition = "TEXT")
    private String taskData;

    /**
     * 重试次数
     */
    @Column(nullable = false)
    @Builder.Default
    private Integer retryCount = 0;

    /**
     * 最大重试次数
     */
    @Column(nullable = false)
    @Builder.Default
    private Integer maxRetryCount = 3;

    /**
     * 错误信息
     */
    @Column(columnDefinition = "TEXT")
    private String errorMessage;

    /**
     * 任务结果（JSON格式）
     */
    @Column(columnDefinition = "TEXT")
    private String taskResult;

    /**
     * 开始处理时间
     */
    private LocalDateTime startedAt;

    /**
     * 完成时间
     */
    private LocalDateTime completedAt;

    /**
     * 创建时间
     */
    @CreatedDate
    @Column(nullable = false, updatable = false)
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @LastModifiedDate
    private LocalDateTime updatedAt;

    /**
     * 是否已通知用户
     */
    @Column(nullable = false)
    @Builder.Default
    private Boolean notified = false;
}

